import json

from django.db.models import Q

from myapp import models
from myapp.utils import getPublicData


def getPageData():
    return list(getPublicData.educations.keys()), getPublicData.workExperience


def getBarData(defaultEducational, defaultExperience):
    if defaultEducational == '不限' and defaultExperience == '不限':
        jobs = getPublicData.getAllJobs()
    elif defaultEducational == '不限':
        jobs = models.JobInfo.objects.filter(workExperience=defaultExperience).all()
    elif defaultExperience == '不限':
        jobs = models.JobInfo.objects.filter(educational=defaultEducational).all()
    else:
        jobs = models.JobInfo.objects.filter(educational=defaultEducational, workExperience=defaultExperience).all()

    print(f'---------- jobs: {len(jobs)}')
    jobType = {}
    for j in jobs:
        try:
            if j.pratice > 0:
                continue

            if jobType.get(j.type, -1) == -1:
                # [2000, 3000]
                jobType[j.type] = [json.loads(j.salary)[1]]
            else:
                jobType[j.type].append(json.loads(j.salary)[1])
        except Exception as err:
            print(f'-----t: {j}, e:{err}')
            continue

    barData = {}
    for k, v in jobType.items():
        if not barData.get(k, 0):
            # [0, 0, 0, 0, 0]
            barData[k] = [i for i in range(5)]
        for i in v:
            s = i /1000
            if s < 10:
                barData[k][0] += 1
            elif s >= 10 and s < 20:
                barData[k][1] += 1
            elif s >= 20 and s < 30:
                barData[k][2] += 1
            elif s >= 30 and s < 40:
                barData[k][3] += 1
            else:
                barData[k][4] += 1

    legends = list(barData.keys())
    if len(legends) == 0: legends = None

    print(jobType.keys())
    print(barData)
    print(legends)


    return getPublicData.salaryList, barData, legends


# 求平均值
def averageFn(lists):
    total = 0
    for i in lists:
        total += i
    return round(total / len(lists), 1)

def getPieData():
    jobs = getPublicData.getAllJobs()
    jobType = {}
    for j in jobs:
        if j.pratice == 1:
            if jobType.get(j.type, -1) == -1:
                # [30, 35]
                jobType[j.type] = [json.loads(j.salary)[1]]
            else:
                jobType[j.type].append(json.loads(j.salary)[1])

    result = []
    for k, v in jobType.items():
        result.append({
            'name': k,
            'value': averageFn(v)
        })

    print(result)
    return result


def getFunnelData():
    jobs = models.JobInfo.objects.filter(~Q(salaryMonth='0')).all()
    data = {}
    for j in jobs:
        x = j.salaryMonth + '薪'
        if data.get(x, -1) == -1:
            data[x] = 1
        else:
            data[x] += 1

    result = []
    for k, v in data.items():
        result.append({
            'name': k,
            'value': v
        })

    return result
